package com.example.demo.study.thread.threadPool;

import org.checkerframework.checker.units.qual.A;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolExecutorTry {
    public static void main(String[] args) {
        int corePoolSize=2;
        int maximumPoolSize=4;
        long keepAliveTime=60;
        TimeUnit unit=TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(10);
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        List<Future<Integer>> list=new ArrayList<>();
        for(int i=0;i<5;i++)
        {
            final int taskId=i;
            Future<Integer> future = threadPool.submit(() -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务" + taskId + " " + Thread.currentThread().getName() + "  完成");
                return taskId;
            });
            list.add(future);
        }
        //不允许提交新任务，但是会处理线程池+阻塞队列的任务
        threadPool.shutdown();

        //awaitTermination 在调用shutdown或者shutdownNow之后，会阻塞当前线程，等待所有任务执行完成或达到超时时间
        //如果在参数设置时间内仍未完成，会返回false，否则返回true
        try {
            if (!threadPool.awaitTermination(60, TimeUnit.SECONDS)) {
                threadPool.shutdownNow();
            }else
            {
                for(Future<Integer> item:list)
                {
                    System.out.println("获取运行结果:"+item.get());
                }
            }
        }catch (InterruptedException | ExecutionException e)
        {
            e.printStackTrace();
            threadPool.shutdownNow();
        }
        System.out.println("all task finished!");
    }
}
